package net.wnb.mineclearance.helper;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import net.wnb.mineclearance.model.Game;
import wnb.util.helper.Converter;
import wnb.util.io.FileManager;
import wnb.util.io.FileSource;
import wnb.util.io.Terminal;

public class GameManager {
	public static final String SAVED_GAME_FILE_NAME = "res/saved.game";//游戏保存文件
	
	//将游戏写入文件
	public static void write(Game game){
		try{			
			OutputStream os = FileManager.getOutputStream(SAVED_GAME_FILE_NAME, FileSource.FILE_SYSTEM);			
			int rowCount = game.getRowCount();
			int colCount = game.getColCount();
			os.write(rowCount);
			os.write(colCount);

			//写入地图
			boolean[] buf = new boolean[rowCount * colCount];
			for(int i=0;i<rowCount;i++){
				for(int j=0;j<colCount;j++){
					buf[i * colCount + j] = game.getValueAt(i, j);
				}
			}
			os.write(Converter.booleanArrayToByteArray(buf));
			
			//写入掩码
			for(int i=0;i<rowCount;i++){
				for(int j=0;j<colCount;j++){
					buf[i * colCount + j] = game.getMaskAt(i, j);
				}
			}
			os.write(Converter.booleanArrayToByteArray(buf));
			
			//写入时长
			os.write(game.getRunningTime());
			
			os.flush();
			os.close();
		}catch(IOException ex){
			Terminal.writeLine(ex.getMessage());
			ex.printStackTrace();
		}
	}
	
	//查看是否存在已保存的游戏
	public static boolean savedGameExists() {
		File file = new File(SAVED_GAME_FILE_NAME);
		return file.exists();
	}

	//读取游戏
	public static Game read() {
		Game game = null;
		
		try {
			InputStream is = FileManager.getInputStream(SAVED_GAME_FILE_NAME, FileSource.FILE_SYSTEM);
			int rowCount = is.read();
			int colCount = is.read();
			
			int len = rowCount * colCount / Converter.BOOLEAN_COUNT_EACH_BYTE;
			byte[] buf = new byte[len];
			if(len != is.read(buf)){
				throw new IOException();
			}			
			boolean[] map = Converter.byteArrayToBooleanArray(buf);
			
			buf = new byte[len];
			if(len != is.read(buf)){
				throw new IOException();
			}
			boolean[] mask = Converter.byteArrayToBooleanArray(buf);
			
			int runningTime = is.read();
			
			is.close();
			game = new Game(rowCount, colCount, map, mask, runningTime);
		} catch (IOException ex) {
			Terminal.writeLine(ex.getMessage());
			ex.printStackTrace();
		}
		
		return game;
	}

	public static void delete() {
		File f = new File(SAVED_GAME_FILE_NAME);
		if(f.exists()){
			f.delete();
		}
	}
}
